/*
 * Copyright © 2011 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */

package com.nokia.example.battletank;

public class PointerEventHandler {
    private static final int MOVE_THRESHOLD = 10;
    private final Listener listener;
    private final int moveThreshold;

    private int x0 = 0;
    private int y0 = 0;

    private int softKeyTop;
    private int leftSoftKeyRight;
    private int rightSoftKeyLeft;

    public PointerEventHandler(int w, int h, Listener l) {
        listener = l;
        moveThreshold = Math.min(w, h)*MOVE_THRESHOLD/100;
        setSize(w, h);
    }

    public final void setSize(int w, int h) {
        softKeyTop = h - h/10;
        leftSoftKeyRight = w/3;
        rightSoftKeyLeft = w - w/3;
    }

    public void pointerPressed(int x, int y) {
        x0 = x;
        y0 = y;
    }

    public void pointerDragged(int x, int y) {
    }

    public void pointerReleased(int x, int y) {
        if(handleSoftKeys(x, y)) return;
        if(handleMovement(x, y)) return;
        handleFire();
    }

    private boolean handleSoftKeys(int x, int y) {
        if(x < leftSoftKeyRight && y > softKeyTop) {
            listener.onLeftSoftKey();
            return true;
        }
        if(x > rightSoftKeyLeft && y > softKeyTop) {
            listener.onRightSoftKey();
            return true;
        }
        return false;
    }

    private boolean handleMovement(int x, int y) {
        int dx = x - x0;
        int adx = Math.abs(dx);
        int dy = y - y0;
        int ady = Math.abs(dy);
        if(Math.max(adx, ady) < moveThreshold) return false;

        if(adx > ady) {
            if(dx > 0) listener.onMoveRight();
            else listener.onMoveLeft();
        } else {
            if(dy > 0) listener.onMoveDown();
            else listener.onMoveUp();
        }
        return true;
    }

    private void handleFire() {
        listener.onFire();
    }

    public static interface Listener {
        void onMoveLeft();
        void onMoveRight();
        void onMoveUp();
        void onMoveDown();
        void onFire();
        void onLeftSoftKey();
        void onRightSoftKey();
    }
}
